package com.library.common.gdxx.push;

import com.alibaba.fastjson2.JSON;
import com.library.common.annotation.Log;
import com.library.common.config.PushConfig;
import com.library.common.gdxx.SignHandle;
import com.library.common.gdxx.domain.req.BookBorrowPushReq;
import com.library.common.gdxx.domain.req.BookInfoPushReq;
import com.library.common.gdxx.domain.resp.GDXXResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @Package: com.library.common.push
 * @ClassName: InternalPush
 * @Author: Yin
 * @Date: 9:54
 * @Description: 内部的推送（推送数据到指定地址 GDXX 广东学心教育开放平台）
 */
@Data
@Slf4j
@Component
public class InternalPush {

    @Resource
    private PushConfig config;

    @Resource
    private SignHandle signHandle;

    @Resource
    private RestTemplate restTemplate;

    /** 推送书籍信息 */
    @Log(title = "推送书籍信息")
    public GDXXResponse bookInfo(List<BookInfoPushReq> bookInfo) {
        Objects.requireNonNull(bookInfo,"书籍信息是必要的");
        try{
            // 推送的参数对象
            String params = JSON.toJSONString(bookInfo);
            // 请求
            HttpEntity<String> request = new HttpEntity<>(params,signHandle.handle(params));
            return restTemplate.postForObject(pushBookInfo(), request, GDXXResponse.class);
        }catch (Exception e) {
            String msg = "[" + config.getHost() + ":" + config.getPort() + "]书籍推送失败：" + e.getMessage();
            log.error("书籍推送失败:{}",msg);
            throw new RuntimeException(msg);
        }
    }

    /** 推送借阅书籍信息 */
    @Log(title = "推送借阅书籍信息")
    public GDXXResponse bookBorrowInfo(List<BookBorrowPushReq> bookBorrowInfo) {
        Objects.requireNonNull(bookBorrowInfo,"书籍借阅信息是必要的");
        try{
            // 推送的参数对象
            String params = JSON.toJSONString(bookBorrowInfo);
            // 请求
            HttpEntity<String> request = new HttpEntity<>(params,signHandle.handle(params));
            return restTemplate.postForObject(pushBookBorrowInfo(), request, GDXXResponse.class);
        }catch (Exception e) {
            String msg = "[" + config.getHost() + ":" + config.getPort() + "]书籍借阅推送失败：" + e.getMessage();
            log.error("书籍借阅推送失败:{}",msg);
            throw new RuntimeException(msg);
        }
    }


    /** 推送一个图书信息 */
    private String pushBookInfo() {
        return String.format("http://%s:%d/v1/open/book/add-book",config.getHost(),config.getPort());
    }

    /** 推送一个图书借阅信息 */
    private String pushBookBorrowInfo() {
        return String.format("http://%s:%d/v1/open/book/add-book-borrow",config.getHost(),config.getPort());
    }

}
